<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\model\EntityModel;
use common\service\TaskGenerateService;
use malkusch\lock\mutex\PHPRedisMutex;
use support\bootstrap\Redis;
use Throwable;
use Webman\Stomp\Client;
use Webman\Stomp\RetryAbleConsumer;

class GenerateEntityStepCategoryTaskConsumer extends BaseConsumer implements RetryAbleConsumer
{

    // 要消费的队列名
    public $queue = 'generate_entity_step_category_task';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * 项目实体生成任务缓存key
     * @param $uniqueStr
     * @return string
     */
    public function getUniqueKey($uniqueStr)
    {
        return $this->queue . $uniqueStr;
    }

    /**
     * 消费
     * @param $data
     * @throws \Exception
     */
    public function doConsume($data)
    {
        $key = $this->getUniqueKey("-{$data['project_id']}-{$data['module_code']}");
        request()->getModuleCode($data['module_code']);
        $mutex = new PHPRedisMutex([Redis::connection()->client()], $key, $this->getTtr() * 2);
        $mutex->synchronized(function () use ($data) {
            $entity = model(EntityModel::class)->where(['id' => ['IN', $data['entity_id_str']]])->find();
            if (!empty($entity)) {
                request()->getTenantId($entity['tenant_id']);
                request()->getUserId($entity['created_by']);
            }

            $taskGenerateService = TaskGenerateService::getInstance();
            $res = $taskGenerateService->doGenerateEntityStepCategoryTask($data['project_id'], $data['module_code'], $data['entity_id_str'], $entity['tenant_id']);

            APP_DEBUG && trace("doGenerateEntityStepCategoryTask result", 'DEBUG');
            APP_DEBUG && trace(var_export($res, true), 'DEBUG');
        });
    }

    public function getTtr()
    {
        return 10;
    }

    public function canRetry($attempt, $error)
    {
        trace(format_exception_info($error), 'ERR');
        return $attempt <= 3;
    }
}
